<template>
  <div :class="{fullscreen:fullscreen}" class="tinymce-container" :style="{width:containerWidth}">
    <textarea :id="tinymceId" class="tinymce-textarea" />
    <div class="editor-custom-btn-container">
      <editorImage v-if="readonlyOrno==0" color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
    </div>
  </div>
</template>

<script>
  /**
   * docs:
   * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
   */
  import editorImage from './components/EditorImage'
  import plugins from './plugins'
  import toolbar from './toolbar'
  import load from './dynamicLoadScript'

  // why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
  const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'

  export default {
    name: 'Tinymce',
    components: { editorImage },
    props: {
      id: {
        // 富文本编辑器的id
        type: String,
        default: function() {
          return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
        }
      },
      value: {
        type: String,
        default: ''
      },

      editorNum: {
        type: Number,
        default: 10
      },


      toolbar: {
        // 工具栏
        type: Array,
        required: false,
        default() {
          return []
        }
      },
      menubar: {
        // 菜单栏
        type: String,
        default: 'file edit insert view format table'
      },
      height: {
        // 富文本编辑器的高
        type: [Number, String],
        required: false,
        default: 360
      },
      width: {
        // 富文本编辑器的宽
        type: [Number, String],
        required: false,
        default: 'auto'
      },
      readonly: {
        // 富文本是否只读
        type: [Number, String],
        required: false,
        default: 0
      }
    },
    data() {
      return {
        hasChange: false, // 内容是否变化
        hasInit: false, // 初始化
        tinymceId: this.id, // 富文本id
        fullscreen: false, // 全屏
        readonlyOrno: ''// 是否为只读
      }
    },
    computed: {
      containerWidth() {
        const width = this.width
        if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
          return `${width}px`
        }
        return width
      }
    },
    watch: {
      value(val) {
        if (!this.hasChange && this.hasInit) {
          this.$nextTick(() =>
            window.tinymce.get(this.tinymceId).setContent(val || ''))
          // 这里往下才是重头戏
          // str是获取的富文本解析成html格式的文本内容

          var str = window.tinymce.activeEditor.getContent();
          // num是用正则获取到的纯文本内容（包括标点符号）,正则函数方法写在下方
          var num = this.removeHTMLTag(str);
          if (num.length > this.editorNum) {
            this.$confirm('字符已超出上限，请修改后重新输入！', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            });
          }
        }
      },
      readonly(val, oldVal) {
        this.readonlyOrno = val
      },

      
    },
    mounted() {
      this.readonlyOrno = this.readonly
      this.init()
    },
    activated() {
      if (window.tinymce) {
        this.initTinymce()
      }
    },
    deactivated() {
      this.destroyTinymce()
    },
    destroyed() {
      this.destroyTinymce()
    },
    methods: {
      removeHTMLTag: function (str) {
        str = str.replace(/<\/?[^>]*>/g, '');
        str = str.replace(/[ | ]*\n/g, '\n');
        str = str.replace(/&nbsp;/ig, '');
        str = str.replace(/\s/g, '');
        return str;
      },
      init() {
        // dynamic load tinymce from cdn
        load(tinymceCDN, (err) => {
          if (err) {
            this.$message.error(err.message)
            return
          }
          this.initTinymce()
        })
      },
      initTinymce() {
        const _this = this
        window.tinymce.init({
          statusbar:true,
          selector: `#${this.tinymceId}`, // 操作的对象
          language: 'zh_CN', // 语言
          height: this.height,
          body_class: 'panel-body ',
          readonly: this.readonlyOrno,
          object_resizing: false, // 是否允许编辑图片
          toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar, // 工具栏
          menubar: this.menubar, // 菜单栏
          plugins: plugins, // 插件
          end_container_on_empty_block: true, // 是否允许回车
          powerpaste_word_import: 'clean',
          code_dialog_height: 450,
          code_dialog_width: 1000,
          advlist_bullet_styles: 'square', // 默认的无序列表标记
          advlist_number_styles: 'default', // 默认的有序列表标记
          imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'], // 图片跨域请求用的
          default_link_target: '_blank', // 链接的默认打开形式
          link_title: false,
          nonbreaking_force_tab: true, // 插入不间断空格需要不间断空格插件
          init_instance_callback: editor => {
            if (_this.value) {
              editor.setContent(_this.value)
            }
            _this.hasInit = true
            editor.on('NodeChange Change KeyUp SetContent', () => {
              this.hasChange = true
              this.$emit('input', editor.getContent())
            })
          },
          setup(editor) {
            editor.on('FullscreenStateChanged', (e) => {
              _this.fullscreen = e.state
            })
          }
          // 整合七牛上传
          // images_dataimg_filter(img) {
          //   setTimeout(() => {
          //     const $image = $(img);
          //     $image.removeAttr('width');
          //     $image.removeAttr('height');
          //     if ($image[0].height && $image[0].width) {
          //       $image.attr('data-wscntype', 'image');
          //       $image.attr('data-wscnh', $image[0].height);
          //       $image.attr('data-wscnw', $image[0].width);
          //       $image.addClass('wscnph');
          //     }
          //   }, 0);
          //   return img
          // },
          // images_upload_handler(blobInfo, success, failure, progress) {
          //   progress(0);
          //   const token = _this.$store.getters.token;
          //   getToken(token).then(response => {
          //     const url = response.data.qiniu_url;
          //     const formData = new FormData();
          //     formData.append('token', response.data.qiniu_token);
          //     formData.append('key', response.data.qiniu_key);
          //     formData.append('file', blobInfo.blob(), url);
          //     upload(formData).then(() => {
          //       success(url);
          //       progress(100);
          //     })
          //   }).catch(err => {
          //     failure('出现未知问题，刷新页面，或者联系程序员')
          //     console.log(err);
          //   });
          // },
        })
      },
      // 销毁Tinymce
      destroyTinymce() {
        const tinymce = window.tinymce.get(this.tinymceId)
        if (this.fullscreen) {
          tinymce.execCommand('mceFullScreen')
        }

        if (tinymce) {
          tinymce.destroy()
        }
      },
      // 新建内容
      setContent(value) {
        window.tinymce.get(this.tinymceId).setContent(value)
      },
      // 获取内容
      getContent() {
        window.tinymce.get(this.tinymceId).getContent()
      },
      // 在富文本编辑器中显示图片列表
      imageSuccessCBK(arr) {
        const _this = this
        arr.forEach(v => {
          window.tinymce.get(_this.tinymceId).insertContent(`<img style="100px" src="${v.url}" >`)
        })
      }
    }
  }
</script>

<style scoped>
  .tinymce-container {
    position: relative;
    line-height: normal;
  }
  .tinymce-container>>>.mce-fullscreen {
    z-index: 10000;
  }
  .tinymce-textarea {
    visibility: hidden;
    z-index: -1;
  }
  .editor-custom-btn-container {
    position: absolute;
    right: 4px;
    top: 4px;
    /*z-index: 2005;*/
  }
  .fullscreen .editor-custom-btn-container {
    z-index: 10000;
    position: fixed;
  }
  .editor-upload-btn {
    display: inline-block;
  }
</style>
<style>
  .mce-branding.mce-widget.mce-label.mce-flow-layout-item.mce-last{
    display: none;
  }
</style>
